import datetime, time

class DatePeriod:
	def __init__(self,today='',year=''):
		''' Please Give Date String like 'YYYYMMDD' '''
		if not today:
			today = self.SingleDay('-1')
		self.__year, self.__mon, self.__day = int(today[:4]),int(today[4:6]),int(today[6:])
		self.__Quarter = {'first_quarter_day':datetime.datetime(self.__year,1,1),'second_quarter_day':datetime.datetime(self.__year,3,31),'third_quarter_day':datetime.datetime(self.__year,6,30),'forth_quarter_day':datetime.datetime(self.__year,9,30)} 

	def DayRange(self,days):
		return map(lambda x:''.join(str(datetime.datetime(self.__year, self.__mon, self.__day)-datetime.timedelta(days=x)).split(' ')[0].split('-')), range(int(days)+1))

	def SingleDay(self,dayDis):
		''' PAY ATTENTION '''
		return ''.join(str(datetime.date.today()+datetime.timedelta(days=int(dayDis))).split('-'))

	def Period(self, Qstring, Endstring=''):
		if Endstring:
			year, mon, day = Endstring.split('-')
			#return (datetime.datetime(int(year), int(mon), int(day))-self.__Quarter[Qstring]+datetime.timedelta(days=1)).days
			return (datetime.datetime(int(year), int(mon), int(day))-self.__Quarter[Qstring]).days
		else:
			#return (datetime.datetime(self.__year, self.__mon, self.__day)-self.__Quarter[Qstring]+datetime.timedelta(days=1)).days
			return (datetime.datetime(self.__year, self.__mon, self.__day)-self.__Quarter[Qstring]).days

	def QuarterJudge(self,dateObj):
		nowQuarter = 'first_quarter_day'
		for tmpName,tmpObj in sorted(self.__Quarter.items(), key=lambda x: (x[1],x[0])):
			if dateObj > tmpObj:
				nowQuarter = tmpName
		return nowQuarter

	def Time2Posixtime(self, timestr):
		''' timestr fmt: dd:mm:yyyy:hh:mm:ss. Because of Apache Log FMT '''
		int_d, int_m, int_y, int_h, int_min, int_s = map(int, timestr.split(':'))
		return time.mktime(datetime.datetime(int_y, int_m, int_d, int_h, int_min, int_s).timetuple())

	def MonConvert(self,monStr):
		''' Aug -> '08' '''
		tmpHash = {'Jan':'1', 'Feb':'2', 'Mar':'3', 'Apr':'4', 'May':'5', 'Jun':'6', 'Jul':'7', 'Aug':'8', 'Sep':'9', 'Oct':'10', 'Nov':'11', 'Dec':'12'}
		return tmpHash[monStr]
